package cn.fzkj.springcloud.loadbalance;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoadBalance implements ILoad{

    private AtomicInteger nextAtomicInteger = new AtomicInteger(0);

    private final int incrementAndGetModulo(){
        int current;
        int next;
        do {
            current = this.nextAtomicInteger.get();
            System.out.println("当前第 " + current +" 次访问");
            if (current >= Integer.MAX_VALUE){
                current = 1;
            }
            next = current + 1;
        }while (!nextAtomicInteger.compareAndSet(current, next));
        return next;
    }

    @Override
    public ServiceInstance getInstance(List<ServiceInstance> instances) {
        int index = incrementAndGetModulo() % instances.size();
        return instances.get(index);
    }
}
